package com.zbkj.dal.feign.client;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.zbkj.dal.common.exception.CrmebException;
import com.zbkj.dal.feign.WeWorkFeign;
import com.zbkj.dal.feign.enums.ContractMeSceneEnums;
import com.zbkj.dal.feign.enums.ContractMeTypeEnums;
import com.zbkj.dal.feign.req.EmployeeListReq;
import com.zbkj.dal.feign.req.QrcodeReq;
import com.zbkj.dal.feign.req.RobotMessage;
import com.zbkj.dal.feign.req.WeWorkUpdateUserReq;
import com.zbkj.dal.feign.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author JXY
 */
@Slf4j
@Component
public class WeWorkFeignClient {

    @Resource
    private WeWorkFeign weWorkFeign;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Value("${we-work.corp.id}")
    private String corpId;

    @Value("${we-work.corp.secret}")
    private String corpSecret;

    @Value("${we-work.books.notify.secret}")
    private String booksSecret;

    @Value("${we-work.corp.robot-key}")
    private String robotKey;

    private static final String WEWORK_ACCESS_TOKEN_CACHE_KEY = "WEWORK_ACCESS_TOKEN_CACHE_KEY";
    private static final Integer WEWORK_ACCESS_TOKEN_EXPIRE_TIME = 5400;

    public void sendMessage(String message) {
        Object res = weWorkFeign.sendMessage(robotKey, RobotMessage.generate(message));
        JSON json = JSONUtil.parse(res);
        Map map = json.toBean(Map.class);
        if ("0".equals(map.get("errcode").toString())) {
            return;
        }
        log.error("发送企微信息失败，消息为：{}，响应结果如下:{}", message, JSONUtil.toJsonStr(res));
    }

    public void deleteEmployee(String wxWorkUserId) {
        String accessToken = accessToken(booksSecret);
        BaseResponse response = weWorkFeign.deleteUser(accessToken, wxWorkUserId);
        if (response.isSuccess()) {
            return;
        }
        throw new CrmebException("删除企业成员失败" + response.getErrMsg());
    }

    public void updateEmployeeAlias(String wxWorkUserId, String alias) {
        String accessToken = accessToken(booksSecret);
        WeWorkUpdateUserReq req = new WeWorkUpdateUserReq();
        req.setUserId(wxWorkUserId);
        req.setAlias(alias);
        BaseResponse response = weWorkFeign.updateUser(accessToken, req);
        if (response.isSuccess()) {
            return;
        }
        throw new CrmebException("更新企业成员别名失败" + response.getErrMsg());
    }

    public List<EmployeeInfo> employeeList() {
        EmployeeListReq employeeListReq = new EmployeeListReq();
        employeeListReq.setLimit(1000);
        EmployeeListVO employeeListVO = weWorkFeign.employeeList(accessToken(booksSecret), employeeListReq);
        if (Objects.nonNull(employeeListVO) && employeeListVO.isSuccess()) {
            return employeeListVO.getDeptUser();
        }
        throw new RuntimeException("获取企业微信成员信息失败：" + employeeListVO.getErrMsg());
    }

    public String weWorkUserName(String weworkUserId) {
        WeWorkUserInfoVO weWorkUserInfoVO = weWorkFeign.weWorkUserInfo(accessToken(corpSecret), weworkUserId);
        if (weWorkUserInfoVO.isSuccess()) {
            return weWorkUserInfoVO.getName();
        }
        throw new RuntimeException("获取企业微信用户信息失败：" + weWorkUserInfoVO.getErrMsg());
    }

    public String createContractMeQrcode(String weworkUserId) {
        QrcodeReq qrcodeReq = new QrcodeReq();
        qrcodeReq.setType(ContractMeTypeEnums.SINGLE.getCode());
        qrcodeReq.setScene(ContractMeSceneEnums.QRCODE.getCode());
        List<String> userIds = new ArrayList<>();
        userIds.add(weworkUserId);
        qrcodeReq.setUser(userIds);
        ContactMeVO contactMeVO = weWorkFeign.qrcode(accessToken(corpSecret), qrcodeReq);
        if (contactMeVO.isSuccess()) {
            return contactMeVO.getQrCode();
        }
        throw new RuntimeException("获取企业微信用户联系我二维码失败：" + contactMeVO.getErrMsg());
    }

    private String accessToken(String secret) {
        String accessToken = redisTemplate.opsForValue().get(WEWORK_ACCESS_TOKEN_CACHE_KEY + secret);
        if (StrUtil.isNotBlank(accessToken)) {
            return accessToken;
        }
        WeWorkTokenVO weWorkTokenVO = weWorkFeign.getToken(corpId, secret);
        if (weWorkTokenVO.isSuccess()) {
            redisTemplate.opsForValue().set(WEWORK_ACCESS_TOKEN_CACHE_KEY, weWorkTokenVO.getAccessToken(), WEWORK_ACCESS_TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
            return weWorkTokenVO.getAccessToken();
        }
        throw new RuntimeException("获取企业微信token失败：" + weWorkTokenVO.getErrMsg());
    }
}
